package com.zjut.an.acquisition.dao;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.ad.dao.AnAd;
import com.zjut.an.util.module.PageModule;

/**
 * A data access object (DAO) providing persistence and search support for
 * AnAcquisition entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.zjut.an.acquisition.dao.AnAcquisition
 * @author MyEclipse Persistence Tools
 */

public class AnAcquisitionDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(AnAcquisitionDAO.class);
	// property constants
	public static final String AC_ID = "acId";
	public static final String WC_ID = "wcId";
	public static final String AD_ID = "adId";
	public static final String ACQ_NAME = "acqName";
	public static final String STATUS = "status";
	public static final String CURR_NUM = "currNum";
	public static final String CURR_ITEM = "currItem";
	public static final String TOTAL_ITEM = "totalItem";
	public static final String PAUSE_TIME = "pauseTime";
	public static final String PAGE_ENCODING = "pageEncoding";
	public static final String PLAN_LIST = "planList";
	public static final String DYNAMIC_ADDR = "dynamicAddr";
	public static final String DYNAMIC_START = "dynamicStart";
	public static final String DYNAMIC_END = "dynamicEnd";
	public static final String LINKSET_START = "linksetStart";
	public static final String LINKSET_END = "linksetEnd";
	public static final String LINK_START = "linkStart";
	public static final String LINK_END = "linkEnd";
	public static final String TITLE_START = "titleStart";
	public static final String TITLE_END = "titleEnd";
	public static final String KEYWORDS_START = "keywordsStart";
	public static final String KEYWORDS_END = "keywordsEnd";
	public static final String DESCRIPTION_START = "descriptionStart";
	public static final String DESCRIPTION_END = "descriptionEnd";
	public static final String CONTENT_START = "contentStart";
	public static final String CONTENT_END = "contentEnd";
	public static final String PAGINATION_START = "paginationStart";
	public static final String PAGINATION_END = "paginationEnd";
	public static final String QUEUE = "queue";
	public static final String IMG_ACQU = "imgAcqu";
	public static final String CONTENT_PREFIX = "contentPrefix";
	public static final String IMG_PREFIX = "imgPrefix";
	public static final String VIEW_START = "viewStart";
	public static final String VIEW_END = "viewEnd";
	public static final String VIEW_ID_START = "viewIdStart";
	public static final String VIEW_ID_END = "viewIdEnd";
	public static final String VIEW_LINK = "viewLink";
	public static final String RELEASE_TIME_START = "releaseTimeStart";
	public static final String RELEASE_TIME_END = "releaseTimeEnd";
	public static final String AUTHOR_START = "authorStart";
	public static final String AUTHOR_END = "authorEnd";
	public static final String ORIGIN_START = "originStart";
	public static final String ORIGIN_END = "originEnd";
	public static final String RELEASE_TIME_FORMAT = "releaseTimeFormat";

	protected void initDao() {
		// do nothing
	}
	
	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		}
	}

	public void save(AnAcquisition transientInstance) {
		log.debug("saving AnAcquisition instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	
	public void update(AnAcquisition transientInstance) {
		log.debug("updating AnAcquisition instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("updating successful");
		} catch (RuntimeException re) {
			log.error("updating failed", re);
			throw re;
		}
	}

	public void delete(AnAcquisition persistentInstance) {
		log.debug("deleting AnAcquisition instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public void deleteById(final Integer acId) {
		log.debug("deleting AnAcquisition By Id");
		try {
			getHibernateTemplate().execute(new HibernateCallback<String>() {
				public String doInHibernate(Session session) throws HibernateException, SQLException {
					SQLQuery query = session.createSQLQuery("DELETE FROM an_acquisition WHERE ac_id = "+acId);
					try{
						query.executeUpdate();
						return "success";
					}catch (Exception e) {
						e.printStackTrace();
					}
					return "fail";
				}
			});
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	
	public AnAcquisition findById(java.lang.Integer id) {
		log.debug("getting AnAcquisition instance with id: " + id);
		try {
			AnAcquisition instance = (AnAcquisition) getHibernateTemplate()
					.get("com.zjut.an.acquisition.dao.AnAcquisition", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(AnAcquisition instance) {
		log.debug("finding AnAcquisition instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding AnAcquisition instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from AnAcquisition as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByWcId(Object wcId) {
		return findByProperty(WC_ID, wcId);
	}

	public List findByAdId(Object adId) {
		return findByProperty(AD_ID, adId);
	}

	public List findByAcqName(Object acqName) {
		return findByProperty(ACQ_NAME, acqName);
	}

	public List findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List findByCurrNum(Object currNum) {
		return findByProperty(CURR_NUM, currNum);
	}

	public List findByCurrItem(Object currItem) {
		return findByProperty(CURR_ITEM, currItem);
	}

	public List findByTotalItem(Object totalItem) {
		return findByProperty(TOTAL_ITEM, totalItem);
	}

	public List findByPauseTime(Object pauseTime) {
		return findByProperty(PAUSE_TIME, pauseTime);
	}

	public List findByPageEncoding(Object pageEncoding) {
		return findByProperty(PAGE_ENCODING, pageEncoding);
	}

	public List findByPlanList(Object planList) {
		return findByProperty(PLAN_LIST, planList);
	}

	public List findByDynamicAddr(Object dynamicAddr) {
		return findByProperty(DYNAMIC_ADDR, dynamicAddr);
	}

	public List findByDynamicStart(Object dynamicStart) {
		return findByProperty(DYNAMIC_START, dynamicStart);
	}

	public List findByDynamicEnd(Object dynamicEnd) {
		return findByProperty(DYNAMIC_END, dynamicEnd);
	}

	public List findByLinksetStart(Object linksetStart) {
		return findByProperty(LINKSET_START, linksetStart);
	}

	public List findByLinksetEnd(Object linksetEnd) {
		return findByProperty(LINKSET_END, linksetEnd);
	}

	public List findByLinkStart(Object linkStart) {
		return findByProperty(LINK_START, linkStart);
	}

	public List findByLinkEnd(Object linkEnd) {
		return findByProperty(LINK_END, linkEnd);
	}

	public List findByTitleStart(Object titleStart) {
		return findByProperty(TITLE_START, titleStart);
	}

	public List findByTitleEnd(Object titleEnd) {
		return findByProperty(TITLE_END, titleEnd);
	}

	public List findByKeywordsStart(Object keywordsStart) {
		return findByProperty(KEYWORDS_START, keywordsStart);
	}

	public List findByKeywordsEnd(Object keywordsEnd) {
		return findByProperty(KEYWORDS_END, keywordsEnd);
	}

	public List findByDescriptionStart(Object descriptionStart) {
		return findByProperty(DESCRIPTION_START, descriptionStart);
	}

	public List findByDescriptionEnd(Object descriptionEnd) {
		return findByProperty(DESCRIPTION_END, descriptionEnd);
	}

	public List findByContentStart(Object contentStart) {
		return findByProperty(CONTENT_START, contentStart);
	}

	public List findByContentEnd(Object contentEnd) {
		return findByProperty(CONTENT_END, contentEnd);
	}

	public List findByPaginationStart(Object paginationStart) {
		return findByProperty(PAGINATION_START, paginationStart);
	}

	public List findByPaginationEnd(Object paginationEnd) {
		return findByProperty(PAGINATION_END, paginationEnd);
	}

	public List findByQueue(Object queue) {
		return findByProperty(QUEUE, queue);
	}

	public List findByImgAcqu(Object imgAcqu) {
		return findByProperty(IMG_ACQU, imgAcqu);
	}

	public List findByContentPrefix(Object contentPrefix) {
		return findByProperty(CONTENT_PREFIX, contentPrefix);
	}

	public List findByImgPrefix(Object imgPrefix) {
		return findByProperty(IMG_PREFIX, imgPrefix);
	}

	public List findByViewStart(Object viewStart) {
		return findByProperty(VIEW_START, viewStart);
	}

	public List findByViewEnd(Object viewEnd) {
		return findByProperty(VIEW_END, viewEnd);
	}

	public List findByViewIdStart(Object viewIdStart) {
		return findByProperty(VIEW_ID_START, viewIdStart);
	}

	public List findByViewIdEnd(Object viewIdEnd) {
		return findByProperty(VIEW_ID_END, viewIdEnd);
	}

	public List findByViewLink(Object viewLink) {
		return findByProperty(VIEW_LINK, viewLink);
	}

	public List findByReleaseTimeStart(Object releaseTimeStart) {
		return findByProperty(RELEASE_TIME_START, releaseTimeStart);
	}

	public List findByReleaseTimeEnd(Object releaseTimeEnd) {
		return findByProperty(RELEASE_TIME_END, releaseTimeEnd);
	}

	public List findByAuthorStart(Object authorStart) {
		return findByProperty(AUTHOR_START, authorStart);
	}

	public List findByAuthorEnd(Object authorEnd) {
		return findByProperty(AUTHOR_END, authorEnd);
	}

	public List findByOriginStart(Object originStart) {
		return findByProperty(ORIGIN_START, originStart);
	}

	public List findByOriginEnd(Object originEnd) {
		return findByProperty(ORIGIN_END, originEnd);
	}

	public List findByReleaseTimeFormat(Object releaseTimeFormat) {
		return findByProperty(RELEASE_TIME_FORMAT, releaseTimeFormat);
	}

	public List findAll() {
		log.debug("finding all AnAcquisition instances");
		try {
			String queryString = "from AnAcquisition";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public AnAcquisition merge(AnAcquisition detachedInstance) {
		log.debug("merging AnAcquisition instance");
		try {
			AnAcquisition result = (AnAcquisition) getHibernateTemplate()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(AnAcquisition instance) {
		log.debug("attaching dirty AnAcquisition instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(AnAcquisition instance) {
		log.debug("attaching clean AnAcquisition instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static AnAcquisitionDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (AnAcquisitionDAO) ctx.getBean("AnAcquisitionDAO");
	}
	
	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final AnAcquisition instance){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(AnAcquisition.class);

			if (!isEmpty(instance.getAcqName())) {
				criteria.add(Restrictions.like(ACQ_NAME, instance.getAcqName(),MatchMode.ANYWHERE));
			}
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(instance), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final AnAcquisition instance) {
		log.debug("finding the number of AnAd instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(AnAcquisition.class);
			if (!isEmpty(instance.getAcqName())) {
				criteria.add(Restrictions.like(ACQ_NAME, instance.getAcqName(),MatchMode.ANYWHERE));
			}
			
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of AnAcquisition instance failed", re);
			throw re;
		}
	}
	
	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}
}